package com.liu.controller;

import com.liu.common.exception.FileNotExistException;
import com.liu.common.exception.FileSizeLimiException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
public class UploadController {


    @Value("${spring.servlet.multipart.max-file-size}")
    long maxFileSiz;

    private final String BASEDIR = "/attchment";//所有上传文件的根目录

    /**
     * 单文件上传
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public String upload(MultipartFile file, HttpServletRequest request){
        //System.out.println();
        return toUpload(file,request,null);
    }

    /**
     * 多文件上传
     * @param files
     * @param request
     * @return
     */
    @PostMapping("/batch/upload")
    public List batchUpdate(List<MultipartFile> files ,HttpServletRequest request){
        List<String> list = new ArrayList<>();
        files.forEach(file->{
            if(!file.isEmpty()){
                String tmp = toUpload(file,request,null);
                list.add(tmp);
            }
        });
        return list;
    }

    /**
     * 上传文件
     * @param file 文件数据
     */
    String toUpload(MultipartFile file,HttpServletRequest request,String type){
        //先判断有咩有附件
        if("".equals(file.getOriginalFilename())){
            throw new FileNotExistException("请选择要上传的文件");
        }

        //获取文件大小
        if(file.getSize()>maxFileSiz){
            throw new FileSizeLimiException("文件大小超过"+(maxFileSiz / (1024*1024))+"M");
        }


        //获取服务器上传的根目录
        FilePath filePath = initDir(request,type);
        String newFile = getNewFileName(file);
        //上传
        try {
                file.transferTo(new File(filePath.getRoot()+"\\"+newFile));
            }catch(IOException e){
                throw new RuntimeException(e);
            }
        return filePath.getDir()+newFile;
    }

    /**
     *初始附件存储目录
     */
    FilePath initDir(HttpServletRequest request,String type){
        if(null == type || "".equals(type)){
            type = "images";
        }
        //获取系统时间
        String relpath = BASEDIR +"/"+type+"/"+getSystemYMD();
        //获取服务器上传的根目录
        String root = request.getServletContext().getRealPath("/")+relpath;
        File dir = new File(root);
        if(!dir.exists()){
            dir.mkdirs();
        }
        return new FilePath(dir.getAbsolutePath(),relpath);
    }

    /**
     * 获取当前系统时间年月日
     */
    String getSystemYMD(){
        LocalDate localDate = LocalDate.now();
        return localDate.format(DateTimeFormatter.ofPattern("yMMdd"));
    }

    /**
     * 获取新文件名
     */
    String getNewFileName(MultipartFile file){
        //获取去原始文件名
        String name = file.getOriginalFilename();
        //获取文件的后缀
        String ext = name.substring(name.lastIndexOf("."));
        //新的文件名
        String newFile = UUID.randomUUID().toString()+ext;
        return newFile;
    }

}
class FilePath {
    String root;//根目录
    String dir;//相对目录

    public FilePath(String root, String dir) {
        this.root = root;
        this.dir = dir;
    }

    public String getRoot() {
        return root;
    }

    public void setRoot(String root) {
        this.root = root;
    }

    public String getDir() {
        return dir;
    }

    public void setDir(String dir) {
        this.dir = dir;
    }
}
